package cn.mw.cmdb.link.controller;

import cn.mw.cmdb.enums.OperatorTypeDescEnum;
import cn.mw.cmdb.link.entity.*;
import cn.mw.cmdb.link.param.LinkParam;
import cn.mw.cmdb.link.service.MwNetWorkLinkService;
import cn.mw.cmdb.mongoMapper.MwNetWorkLinkMapper;
import cn.mw.cmdb.util.CMDBTool;
import cn.mw.log.enums.LogLevel;
import cn.mw.microMonitorCommon.api.cmdb.AssetInfo;
import cn.mw.microMonitorCommon.api.common.BaseApiService;
import cn.mw.microMonitorCommon.api.common.ResponseBase;
import cn.mw.microMonitorCommon.constant.Constants;
import cn.mw.microMonitorCommon.operatorlog.client.MwLogClientSimple;
import cn.mw.microMonitorCommon.operatorlog.enums.MwBusinessLogType;
import cn.mw.microMonitorCommon.security.utils.SecurityUtils;
import cn.mw.microMonitorCommon.util.DateUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 线路功能接口
 */
@RequestMapping("/link")
@Controller
@Tag(name = "线路管理")
@Slf4j
public class MwNetWorkLinkController extends BaseApiService {

    private MwNetWorkLinkService netWorkLinkService;

    private MwLogClientSimple logClientSimple;

    private MessageSource messageSource;

    private MwNetWorkLinkMapper netWorkLinkMapper;

    private final String MENU_NAME = "线路";

    public MwNetWorkLinkController(MwNetWorkLinkService netWorkLinkService,MwLogClientSimple logClientSimple,MessageSource messageSource,MwNetWorkLinkMapper netWorkLinkMapper) {
        this.netWorkLinkService = netWorkLinkService;
        this.logClientSimple = logClientSimple;
        this.messageSource = messageSource;
        this.netWorkLinkMapper = netWorkLinkMapper;
    }

    @PostMapping("/save")
    @ResponseBody
    @Operation(summary = "保存线路信息")
    public ResponseBase save(@RequestBody MwNetWorkLinkDto mwNetWorkLinkDto) throws Exception {
        Boolean flag = true;
        if(StringUtils.isNotEmpty(mwNetWorkLinkDto.getLinkId())){
            flag = false;
        }
        netWorkLinkService.saveLink(mwNetWorkLinkDto);
        if(!flag){
            logClientSimple.addBusinessLog(LogLevel.INFO.getId(), MwBusinessLogType.LINK_MANAGE.getId(),
                    messageSource.getMessage("mwCmdb-operation-log", new Object[]{ SecurityUtils.getUser().getNickName(), DateUtils.now()
                            , MwBusinessLogType.LINK_MANAGE.getCnName(), OperatorTypeDescEnum.update.getCname() + MENU_NAME,
                            OperatorTypeDescEnum.update.getCname() + mwNetWorkLinkDto.getLinkName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));
        }else{
            logClientSimple.addBusinessLog(LogLevel.INFO.getId(), MwBusinessLogType.LINK_MANAGE.getId(),
                    messageSource.getMessage("mwCmdb-operation-log", new Object[]{ SecurityUtils.getUser().getNickName(), DateUtils.now()
                            , MwBusinessLogType.LINK_MANAGE.getCnName(), OperatorTypeDescEnum.add.getCname() + MENU_NAME,
                            OperatorTypeDescEnum.add.getCname() + mwNetWorkLinkDto.getLinkName(), Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));
        }
        return setResultSuccess();
    }

    @PostMapping("/remove")
    @ResponseBody
    @Operation(summary = "删除线路信息")
    public ResponseBase remove(@RequestBody LinkParam linkParam) throws Exception {
        List<MwNetWorkLinkDto> linkDtos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(linkParam.getLinkIds())){
            Query query = new Query();
            query.addCriteria(new Criteria(CMDBTool.getFieldName(MwNetWorkLinkDto::getLinkId)).in(linkParam.getLinkIds()));
            linkDtos = netWorkLinkMapper.find(query);
        }
        netWorkLinkService.delLink(linkParam);
        List<String> collect = linkDtos.stream().map(s -> s.getLinkName()).collect(Collectors.toList());
        String name = String.join(",", collect);
        String nickName = SecurityUtils.getUser().getNickName();
        logClientSimple.addBusinessLog(LogLevel.INFO.getId(), MwBusinessLogType.LINK_MANAGE.getId(),
                messageSource.getMessage("mwCmdb-operation-log", new Object[]{nickName, DateUtils.now()
                        , MwBusinessLogType.LINK_MANAGE.getCnName(), OperatorTypeDescEnum.remove.getCname() + MENU_NAME,
                        OperatorTypeDescEnum.remove.getCname() + name, Constants.OperationStatus.SUCCESS}, LocaleContextHolder.getLocale()));
        return setResultSuccess();
    }

    @PostMapping("/select")
    @ResponseBody
    @Operation(summary = "查询线路信息")
    public ResponseBase select(@RequestBody LinkParam linkParam) throws Exception {
        Page page = netWorkLinkService.selectList(linkParam);
        return setResultSuccess(page);
    }

    @PostMapping("/getDeviceInfo")
    @ResponseBody
    @Operation(summary = "获取设备的信息")
    public ResponseBase getDeviceInfo() throws Exception {
        List<AssetInfo> deviceInfo = netWorkLinkService.getDeviceInfo();
        return setResultSuccess(deviceInfo);
    }

    @PostMapping("/getIpAndInterface")
    @ResponseBody
    @Operation(summary = "获取设备的IP和接口信息")
    public ResponseBase getIpAndPortInfo(@RequestBody LinkParam linkParam) throws Exception {
        MwLinkIpAndInterfaceDto deviceIpAndInterface = netWorkLinkService.getDeviceIpAndInterface(linkParam);
        return setResultSuccess(deviceIpAndInterface);
    }

    @PostMapping("/getBandWidth")
    @ResponseBody
    @Operation(summary = "获取设备的带宽信息")
    public ResponseBase getBandWidth(@RequestBody LinkParam linkParam) throws Exception {
        MwLinkBandWidthDto linkBandWidthInfo = netWorkLinkService.getLinkBandWidthInfo(linkParam);
        return setResultSuccess(linkBandWidthInfo);
    }

    @PostMapping("/getTargetIp")
    @ResponseBody
    @Operation(summary = "获取检测的目标IP信息")
    public ResponseBase getTargetIpInfo(@RequestBody LinkParam linkParam) throws Exception {
        List<MwLinkTargetIpInfo> targetIpInfo = netWorkLinkService.getTargetIpInfo(linkParam);
        return setResultSuccess(targetIpInfo);
    }

    @PostMapping("/getHistoryTrend")
    @ResponseBody
    @Operation(summary = "获取线路的历史趋势数据")
    public ResponseBase getHistoryTrendInfo(@RequestBody LinkParam linkParam) throws Exception {
        List<LinkHistoryTrendDto> linkHistoryTrendInfo = netWorkLinkService.getLinkHistoryTrendInfo(linkParam);
        return setResultSuccess(linkHistoryTrendInfo);
    }

    @PostMapping("/selectLinkById")
    @ResponseBody
    @Operation(summary = "根据ID查询线路数据")
    public ResponseBase selectLinkById(@RequestBody LinkParam linkParam) throws Exception {
        MwNetWorkLinkDto netWorkLinkDto = netWorkLinkService.selectLinkByLinkId(linkParam);
        return setResultSuccess(netWorkLinkDto);
    }

    @PostMapping("/linkTree/save")
    @ResponseBody
    @Operation(summary = "保存线路树结构信息")
    public ResponseBase saveLinkTree(@RequestBody MwLinkTreeDto linkTreeDto) throws Exception {
        netWorkLinkService.saveLinkTree(linkTreeDto);
        return setResultSuccess();
    }

    @PostMapping("/linkTree/remove")
    @ResponseBody
    @Operation(summary = "删除线路树结构信息")
    public ResponseBase removeLinkTree(@RequestBody LinkParam linkParam) throws Exception {
        netWorkLinkService.delLinkTree(linkParam);
        return setResultSuccess();
    }

    @PostMapping("/linkTree/select")
    @ResponseBody
    @Operation(summary = "查询线路树结构信息")
    public ResponseBase selectLinkTree() throws Exception {
        List<MwLinkTreeDto> linkTreeDtos = netWorkLinkService.selectLinkTree();
        return setResultSuccess(linkTreeDtos);
    }

    @PostMapping("/import")
    @ResponseBody
    @Operation(summary = "导入线路数据")
    public ResponseBase importLinkInfo(@RequestBody MultipartFile file,HttpServletResponse response) throws Exception {
        netWorkLinkService.linkImport(file,response);
        return setResultSuccess();
    }

    @GetMapping("/exportTemplate")
    @ResponseBody
    @Operation(summary = "下载线路导入模板")
    public void exportLinkTemplate(HttpServletResponse response) throws Exception {
        netWorkLinkService.exportLinkTemplate(response);
    }

    @PostMapping("/export")
    @ResponseBody
    @Operation(summary = "导出线路")
    public void exportLinkInfo(@RequestBody LinkParam linkParam,HttpServletResponse response) throws Exception {
        netWorkLinkService.linkExport(linkParam,response);
    }
}
